//
//  MCUserCacheInfoManager.m
//  QuKeClient
//
//  Created by delicious on 2018/1/23.
//  Copyright © 2018年 delicious. All rights reserved.
//

#import "MCInfoCacheManager.h"
#import "JQFMDB.h"
#define DBNAME @"cache_data.db"

@interface MCInfoCacheManager()
@property (nonatomic, strong) JQFMDB * FMDB;
@end
// 环信聊天用的昵称和头像（发送聊天消息时，要附带这3个属性）

static NSString *const kChatUserId = @"user_id";// 环信账号
static NSString *const kChatUserNick =@"nickname";
static NSString *const kChatUserPic  =@"avatar_img";
static NSString *const kChatUserGroupId  =@"group_chat_id";

@implementation MCInfoCacheManager

+ (instancetype)sharedCacheManager
{
    static MCInfoCacheManager *cacheManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cacheManager = [[self alloc] init];
        
    });
    return cacheManager;
}

+(void)onCleanTable
{
    MCInfoCacheManager *caheManager = [MCInfoCacheManager sharedCacheManager];
    // `清空表
    [caheManager.FMDB jq_deleteAllDataFromTable:@"userinfo"];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        
       self.FMDB = [JQFMDB shareDatabase:@"cache_data.db"];
        
       BOOL is = [self.FMDB jq_createTable:@"userinfo" dicOrModel:@{@"user_id":@"TEXT",
                                                           @"nickname":@"TEXT",
                                                           @"avatar_img":@"TEXT",
                                                           @"group_chat_id":@"TEXT"
                                                           }];
        NSLog(@"%d",is);
//       [self.FMDB jq_deleteTable:@"userinfo"];

    }
    return self;
}

//+(void)createTable:(FMDatabase *)db
//{
//    if ([db open]) {
//        if (![db tableExists :@"userinfo"]) {
//            if ([db executeUpdate:@"create table userinfo (userid text, username text, userimage text)"]) {
//                NSLog(@"create table success");
//            }else{
//                NSLog(@"fail to create table");
//            }
//        }else {
//            NSLog(@"table is already exist");
//        }
//    }else{
//        NSLog(@"fail to open");
//    }
//}
//+(FMDatabase*)getDB{
//    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
//    NSString *dbPath   = [docsPath stringByAppendingPathComponent:DBNAME];
//    FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];
//    [self createTable:db];
//    return db;
//}

+ (void)clearTableData
{
    MCInfoCacheManager *caheManager = [MCInfoCacheManager sharedCacheManager];
    if ([caheManager.FMDB jq_deleteTable:@"userinfo"]) {
        NSLog(@"clear successed");
    }else{
        NSLog(@"fail to clear");
    }
    
}



+(void)saveModel:(id)user{
//    [MCInfoCacheManager saveInfo:user.EaseMobUserName imgId:user.HeadImg nickName:user.Username];
}

+(void)saveInfo:(NSString *)openId
          imgId:(NSString*)imgId
       nickName:(NSString*)nickName
        groupId:(NSString*)groupId{
    NSMutableDictionary *extDic = [NSMutableDictionary dictionary];
   
    if (openId) {
        [extDic setValue:openId forKey:kChatUserId];
    }
    if (imgId) {
        [extDic setValue:imgId   forKey:kChatUserPic];//完整图片路径"http://img.baidu.com/1234"。如果imgId是相对路径，那完整路径就是类似"http://img.baidu.com/abc.jpg"
        
    }
    if (nickName) {
        [extDic setValue:nickName forKey:kChatUserNick];
    }
    if (groupId) {
        [extDic setValue:groupId forKey:kChatUserGroupId];
    }
    [MCInfoCacheManager saveDict:extDic];
}

+(void)saveInfo:(NSString *)openId
          imgId:(NSString*)imgId
       nickName:(NSString*)nickName{
    NSMutableDictionary *extDic = [NSMutableDictionary dictionary];
    if (openId) {
        [extDic setValue:openId forKey:kChatUserId];
    }
    if (imgId) {
        [extDic setValue:imgId   forKey:kChatUserPic];
    }
    if (nickName) {
        [extDic setValue:nickName forKey:kChatUserNick];
    }
 
    [MCInfoCacheManager saveDict:extDic];
}


+(void)saveDict:(NSDictionary *)userinfo{
    if (userinfo==nil) {
        return;
    }
     MCInfoCacheManager *caheManager = [MCInfoCacheManager sharedCacheManager];
    
    NSString *userid = [userinfo objectForKey:kChatUserId];
    
//    [caheManager.FMDB jq_inDatabase:^{
        NSString *sql = [NSString stringWithFormat:@"WHERE user_id = '%@'",userid];
        NSArray *arr = [caheManager.FMDB jq_lookupTable:@"userinfo" dicOrModel:[MCInfoCache class] whereFormat:sql];
        if (arr.count==0) {
            NSString *sql = [NSString stringWithFormat:@"WHERE user_id = '%@'",userid];
            
            if ([caheManager.FMDB jq_deleteTable:@"userinfo" whereFormat:sql]) {
                NSLog(@"删除成功");
            }else{
                NSLog(@"删除失败");
            }
            if ([caheManager.FMDB jq_insertTable:@"userinfo" dicOrModel:userinfo]) {
                NSLog(@"插入成功");
            }else{
                NSLog(@"插入失败");
            }
        }else
        {
            NSString *nickname = userinfo[@"nickname"];
            NSString *avatar_img = userinfo[@"avatar_img"];
            
            if (kStringIsEmpty(nickname)==NO) {
                [MCInfoCacheManager updateNickName:nickname Userid:userid];
            }
            if (kStringIsEmpty(avatar_img)==NO) {
                [MCInfoCacheManager updateImgId:avatar_img Userid:userid];
            }
        }
//    }];
    
    
}


+(BOOL)updateImgId:(NSString*)imgId Userid:(NSString *)userid
{
    if (imgId==nil) {
        return NO;
    }
    
    MCInfoCacheManager *caheManager = [MCInfoCacheManager sharedCacheManager];
    NSString *sql = [NSString stringWithFormat:@"WHERE user_id = '%@'",userid];
    if ([caheManager.FMDB jq_updateTable:@"userinfo" dicOrModel:@{@"avatar_img":imgId} whereFormat:sql]) {
        NSLog(@"更新成功");
        return YES;
    }else
    {
        NSLog(@"更新失败");
        return NO;
    }
}
    
    
+(BOOL)updateNickName:(NSString*)nickName  Userid:(NSString *)userid
{
    if (nickName==nil) {
        return NO;
    }
    
    MCInfoCacheManager *caheManager = [MCInfoCacheManager sharedCacheManager];
    NSString *sql = [NSString stringWithFormat:@"WHERE user_id = '%@'",userid];
    if ([caheManager.FMDB jq_updateTable:@"userinfo" dicOrModel:@{@"nickname":nickName} whereFormat:sql]) {
        NSLog(@"更新成功");
        return YES;
    }else
    {
        NSLog(@"更新失败");
        return NO;
    }

}
+(MCInfoCache*)queryById:(NSString *)userid
{
    return nil;
}

+(void)queryById:(NSString *)userid queryModel:(infoCacheModel)queryModel{
   
    MCInfoCacheManager *caheManager = [MCInfoCacheManager sharedCacheManager];
    
    [caheManager.FMDB jq_inDatabase:^{
        NSString *sql = [NSString stringWithFormat:@"WHERE user_id = '%@'",userid];
        NSArray *arr = [caheManager.FMDB jq_lookupTable:@"userinfo" dicOrModel:[MCInfoCache class] whereFormat:sql];
        if (arr.count!=0) {
             queryModel(arr.firstObject);
        }else
        {
            queryModel(nil);
        }
    }];
    
}

@end


@implementation MCInfoCache



@end


